const nodemailer = require("nodemailer");
const schedule = require('node-schedule')

const userEmail = "542356155@qq.com" // 写发送人的邮箱
const userName = 'Mrlih <542356155@qq.com>' // 发送人  格式 : 用户名 <XXXX@qq.com>
const pass = "dnpsoekyylsnbbee" //QQ邮箱需要使用授权码
const title1 = '温馨提示！' // 邮件标题
const qqemail1 = '542356155@qq.com' // 接受邮件的qq邮箱
const togetherDate = '2020/8/25/22:00' //开始在一起的时间
const birth = '2021/6/4/00:00' //生日
let n = 1


const sendemail = (title, content, qqemail) => {
	console.log("创建连接");
	let con = nodemailer.createTransport({
		host: "smtp.qq.com", //邮箱服务的主机，如smtp.qq.com
		port: 465, //对应的端口号
		//开启安全连接
		secure: true, // secure:true for port 465, secure:false for port 587
		secureConnection: true, // use SSL

		//用户信息
		auth: {
			user: "542356155@qq.com",
			pass: "dnpsoekyylsnbbee", // QQ邮箱需要使用授权码
		},
	});
	console.log("设置收件人信息");
	//设置收件人信息
	let mailOptions = {
		from: 'Mrlih <542356155@qq.com>', //谁发的 格式必须 ’这里是发件人名字" <xx@qq.com>‘
		to: '542356155@qq.com', // //发给谁
		subject: '温馨提示！', //主题是什么
		// text: "xin", //文本内容
		html: content //"<html><h1>world123</h1></html>", //html模板

		// //附件信息
		// attachments: [
		//   {
		//     filename: "",
		//     path: "",
		//   },
		// ],
	};

	// 使用先前创建的传输器的 sendMail 方法传递消息对象
	let p = new Promise((succ, err) => {
		con.sendMail(mailOptions, (error, info) => {
			if (error) {
				console.log(error);
				err(error)
				return console.log(error);
			} else {
				console.log(`Message: ${info.messageId}`);
				console.log(`sent: ${info.response}`);
				succ(info.response)
			}
		});
	})
	return p
}

function togetherTime() {
	let now = new Date().getTime()
	// 2020/8/25/22:00
	let old = new Date(togetherDate).getTime()
	let time = now - old;
	let day = parseInt(time / 1000 / 60 / 60 / 24);
	let hour = parseInt(time / 1000 / 60 / 60 % 24);
	let minute = parseInt(time / 1000 / 60 % 60);
	// let minute = parseInt(time / 1000 / 60 % 60);
	let seconds = parseInt(time / 1000 % 60);
	// console.log(day,hour,minute,seconds);
	let NowTime = `${day}天${hour}时${minute}分${seconds}秒`;
	return NowTime
}

function birthday() {
	let now = new Date().getTime()
	// 6/4
	let bir = new Date(birth).getTime()
	let time = bir - now;
	let day = parseInt(time / 1000 / 60 / 60 / 24);
	return day
}

console.log('启动成功');
// 每天8点发一次
schedule.scheduleJob('* * 8 * * *', function() {
	let contentText = `<h1 style="color:red">♥已经在一起${togetherTime()}了♥</h1><h1>♥还有${birthday()}天生日了♥</h1>`
	sendemail(title1, contentText, qqemail1).then(res => {
		console.log('发送' + n + '次');
		n++
	})
});
